# import pyfirmata
# import time
#
# #对于连接Arduino的串口创建一个实例
# n = pyfirmata.Arduino('/dev/ttyACM0')
#
# #定义Arduino上连接舵机的数据引脚6号并设为数字信号d
# a = n.get_pin('d:6:s')
#
# #write函数括号内的数值直接写需要舵机所转的角度
# a.write(90)


# import pyfirmata
#
# led_pin = 8
#
# board = pyfirmata.Arduino("/dev/ttyACM0")
#
# while True:
#
#     board.digital[led_pin].write(0)
#
#     board.pass_time(2)
#
#     board.digital[led_pin].write(1)
#
#     board.pass_time(2)


from pymata4 import pymata4
import time

class DigitalInput:
    """
    Set a pin for digital input and received all data changes
    in the callback method
    """
    def __init__(self, pin):
        """
        Set a pin as a digital input
        :param pin: digital pin number
        """

        # Indices into the callback report data
        self.CB_PIN_MODE = 0
        self.CB_PIN = 1
        self.CB_VALUE = 2
        self.CB_TIME = 3

        # Instantiate this class with the pymata4 API
        self.device = pymata4.Pymata4()

        # Set the pin mode and specify the callback method.
        self.device.set_pin_mode_digital_input(pin, callback=self.the_callback)

        # Keep the program running and wait for callback events.
        while True:
            try:
                time.sleep(1)
            # If user hits Control-C, exit cleanly.
            except KeyboardInterrupt:
                self.device.shutdown()

    def the_callback(self, data):
        """
        A callback function to report data changes.
        This will print the pin number, its reported value
        the pin type (digital, analog, etc.) and
        the date and time when the change occurred

        :param data: [pin, current reported value, pin_mode, timestamp]
        """
        # Convert the date stamp to readable format
        date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data[self.CB_TIME]))

        # Print the pin, current value and time and date of the pin change event.
        print(f'Pin: {data[self.CB_PIN]} Value: {data[self.CB_VALUE]} Time Stamp: {date}')

if __name__ == '__main__':
    # Monitor Pin 12 For Digital Input changes
    DigitalInput(12)
